package freedom.ms.auth.controller;

import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import freedom.ms.auth.dao.ErrorRepository;
import freedom.ms.auth.entity.ErrorMessage;

@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	
	@Autowired
   private ErrorRepository errorRepository;

	@ExceptionHandler()
	public String exception(HttpServletRequest request, final Throwable e, Model model) {
		String url = request.getRequestURL().toString();
		Date time = new Date(request.getSession(false).getLastAccessedTime());
		ErrorMessage error = new ErrorMessage(time, url, getStackTrace(e));
		error = errorRepository.save(error);
		if(logger.isErrorEnabled())
			logger.error(error.toString());
		model.addAttribute("errorCode", error.getId());
		return "error";
	}

	public static String getStackTrace(Throwable e) {
		if (e == null)
			return "Unknown error";
		PrintWriter pw = null;
		try {
			ByteArrayOutputStream buf = new java.io.ByteArrayOutputStream();
			pw = new java.io.PrintWriter(buf, true);
			e.printStackTrace(pw);
			pw.close();
			return buf.toString();
		} finally {
			if(pw != null)
				pw.close();
		}
	}

}
